package com.hutao.manage.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hutao.manage.mapper.ScanMapper;
import com.hutao.manage.service.PDFService;
import com.hutao.manage.util.PDFUtil;
import com.hutao.manage.util.StringUtil;
import com.itextpdf.text.DocumentException;

@Service
public class PDFServiceImpl implements PDFService{

	@Autowired
	private ScanMapper scanMapper;
	
	@Override
	public String generatePDFFileName(String onlyId) {
		
		String [] pageNameArr = {"20","30","41","42","32","36","37","33","31","34","10","11","39","43","44","38","47","51","50","52","70","61","62","81","90"};

		String baseDir = "D://MrDoc/sy/";
		String temFileDir = "D://MrDoc/temp/";
		
		List<String> pdfFilePathList = new ArrayList<>();
		//pdfFilePathList.add("D://MrDoc/sy/"+onlyId+".PDF");
		
		List<String> pngFileList = null;
		
		int count =1;
		for (String pageName : pageNameArr) {
			List<String> fileNames = scanMapper.getSaomiaoFileName(onlyId, pageName);
			
			if(CollectionUtils.isEmpty(fileNames)) {
				continue;
			}
			
			
			String pdfPath = StringUtil.getFileName()+".PDF";
			pngFileList = new ArrayList();
			for (String fileName : fileNames) {
				
				File file = new File(baseDir+onlyId+"/"+fileName.replace("tif", "png"));
				if(!file.exists()) {
					continue;
				}
				pngFileList.add(baseDir+onlyId+"/"+fileName.replace("tif", "png"));
			
			}
			if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(pngFileList)) {
				try {
					PDFUtil.Img2PDF(pngFileList, temFileDir+"/"+pdfPath);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				pdfFilePathList.add(temFileDir+"/"+pdfPath);
			}
			
			
			
		}
		List<File> pdfList = new LinkedList<>();
		int i = 0;
		for (String  pdfPath : pdfFilePathList) {
			pdfList.add(new File(pdfPath));
		}
		
		
		try {
			PDFUtil.mergePdf(pdfList.toArray(new File[pdfList.size()]), new File("D://MrDoc/"+onlyId+".pdf"));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(count);
		
		
		
		
		
		
		return null;
	}

	
}
